package com.mjh.zhujianju.service.party.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.model.SysUser;
import com.livew.framework.base.service.FileService;
import com.livew.framework.base.service.SysUserService;
import com.livew.framework.base.service.impl.BaseServiceImpl;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.page.PagedBeanUtil;
import com.livew.framework.page.PagedResult;
import com.livew.framework.utils.XTEntityUtils;
import com.livew.framework.utils.XTListUtils;
import com.mjh.zhujianju.dao.party.BuildingEventMapper;
import com.mjh.zhujianju.enums.BusinessEnum;
import com.mjh.zhujianju.model.agency.RemoveEO;
import com.mjh.zhujianju.model.base.ContentEO;
import com.mjh.zhujianju.model.party.BuildingEventEO;
import com.mjh.zhujianju.model.party.BuildingEventUsersEO;
import com.mjh.zhujianju.service.base.ContentService;
import com.mjh.zhujianju.service.party.BuildingEventSercice;
import com.mjh.zhujianju.service.party.BuildingEventUsersService;
import com.mjh.zhujianju.util.FileUrlAdapter;
import com.mjh.zhujianju.vo.party.BuildingEventUsersVO;
import com.mjh.zhujianju.vo.party.BuildingEventVO;

/**
 * @author liuyang
 * @Description: 活动
 * @date 2018/8/16 22:15
 */
@Service
public class BuildingEventSerciceImpl extends BaseServiceImpl<BuildingEventEO> implements BuildingEventSercice {

    @Autowired
    private FileService fileService;

    @Autowired
    private BuildingEventUsersService buildingEventUsersService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private BuildingEventMapper buildingEventMapper;


    @Autowired
    private SysUserService sysUserService;

    private final String TYPE_START = "1";

    private final String TYPE_OVER = "2";

    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public BuildingEventSerciceImpl(BuildingEventMapper buildingEventMapper) {
        super(buildingEventMapper);
    }

    @Override
    public List<BuildingEventVO> queryBuildingEventIndexList() {
        return queryList(2L,TYPE_START,null);
    }

    @Override
    public List<BuildingEventVO> queryBuildingEventListIndex(String type) {
        List<BuildingEventVO> list= Lists.newArrayList();
        if(type.equals("0")) {
        	list = queryList(null,TYPE_START,null);
        	if (!CollectionUtils.isEmpty(list)){
                initFile(list);
            }
        }else {
        	list = queryList(null,TYPE_OVER,null);
        	if (!CollectionUtils.isEmpty(list)){
                 initMap(list);
                 initFile(list);
            }
        }
        return list;
    }

    private void initMap(List<BuildingEventVO> overList){
        List<Long> ids = overList.stream().map(buildingEventVO -> buildingEventVO.getId()).distinct().collect(Collectors.toList());
        //查询人数
        List<BuildingEventUsersVO> usersVOList = buildingEventUsersService.queryBuildingEventUsersVOByEventIds(ids);
        if (!CollectionUtils.isEmpty(usersVOList)){
            for (BuildingEventVO buildingEventVO : overList){
                for (BuildingEventUsersVO buildingEventUsersVO : usersVOList){
                    if (buildingEventVO.getId().equals(buildingEventUsersVO.getEventId())){
                        buildingEventVO.setJoinUsers(buildingEventUsersVO.getJoinUsers());
                    }
                }
            }
        }
    }

    @Override
    public Map<String, List<BuildingEventVO>> queryBuildingEventList(Long userId) {
        List<BuildingEventUsersEO> list = buildingEventUsersService.queryEventUsersEOById(userId);
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        List<Long> eventIds = list.stream().map(buildingEventUsersEO -> buildingEventUsersEO.getEventId()).distinct().collect(Collectors.toList());
        Map<String,List<BuildingEventVO>> map = Maps.newHashMap();
        List<BuildingEventVO> startList = queryList(null,TYPE_START,eventIds);
        if (!CollectionUtils.isEmpty(startList)){
            initFile(startList);
        }

        List<BuildingEventVO> overList = queryList(null,TYPE_OVER,eventIds);
        if (!CollectionUtils.isEmpty(overList)){
            initMap(overList);
            initFile(overList);
        }
        map.put("start",startList);
        map.put("end",overList);
        return map;
    }

    @Override
    public BuildingEventVO queryBuildingEventInfo(Long id) {
        BuildingEventVO buildingEventVO = new BuildingEventVO();
        BuildingEventEO buildingEventEO = buildingEventMapper.selectByPrimaryKey(id);
        if (buildingEventEO == null){
            return buildingEventVO;
        }
        BeanUtils.copyProperties(buildingEventEO,buildingEventVO);


        buildingEventVO.setRegistrationDeadlineStr(sdf.format(buildingEventVO.getRegistrationDeadline()));
        buildingEventVO.setActiveDateStr(sdf.format(buildingEventVO.getStartTime())+" 至 "+sdf.format(buildingEventVO.getEndTime()));

        //查询内容
        ContentEO contentEO = contentService.queryContentByTypeAndId(BusinessEnum.TYPE_EVENT.getCode(),id);
        if (contentEO != null){
            buildingEventVO.setContent(contentEO.getContent());
        }
        return buildingEventVO;
    }

    @Override
    public PagedResult<BuildingEventVO> findBuildingEventPagination(BuildingEventEO buildingEventEO) {
        Integer pageNo = buildingEventEO.getPageNo() == null ? 1 : buildingEventEO.getPageNo();
        Integer pageSize = buildingEventEO.getPageSize() == null ? 15 : buildingEventEO.getPageSize();
        PageHelper.startPage(pageNo, pageSize);
        List<BuildingEventEO> list = buildingEventMapper.selectPagination(buildingEventEO);
        PagedResult<BuildingEventEO> page = PagedBeanUtil.toPagedResult(list);
        PagedResult<BuildingEventVO> result = new PagedResult<BuildingEventVO>();
        BeanUtils.copyProperties(page, result);

        if (!XTListUtils.isEmpty(list)) {
            List<Long> ids = XTEntityUtils.getIdList(list);
            List<BuildingEventVO> voList = new ArrayList<BuildingEventVO>();
//            Map<Long, FileEO> files = fileService.getMapTopOne(ids, BuildingClassEO.class.getName(), null);
            Map<Long,Long> joinUsersMap = buildingEventUsersService.getMapTopOne(ids);
            for (BuildingEventEO buildingEventEO1 : list) {
                BuildingEventVO d = new BuildingEventVO();
                BeanUtils.copyProperties(buildingEventEO1, d);
                voList.add(d);
                Long joinUsers = joinUsersMap.get(d.getId());
                if(joinUsers != null){
                    d.setJoinUsers(joinUsers.intValue());
                }else {
                    d.setJoinUsers(0);
                }

                d.setRegistrationDeadlineStr(sdf.format(d.getRegistrationDeadline()));
            }
            result.setDataList(voList);
        }
        return result;
    }

    @Override
    public void saveInfo(BuildingEventVO buildingEventVO) throws XTBusinessException {
        BuildingEventEO buildingEventEO = new BuildingEventEO();
        BeanUtils.copyProperties(buildingEventVO, buildingEventEO);
        if (StringUtils.isEmpty(buildingEventEO.getId())) {
            this.save(buildingEventEO);
            if (buildingEventEO.getBasicFunction() != null) {
                contentService.saveOrUpdate(BusinessEnum.TYPE_EVENT.getCode(), buildingEventEO.getId(), buildingEventEO.getBasicFunction());
            }
        } else {
            this.updateByPrimaryKey(buildingEventEO);
            // 更新内容
            contentService.saveOrUpdate(BusinessEnum.TYPE_EVENT.getCode(), buildingEventEO.getId(), buildingEventEO.getBasicFunction());
        }
        if (!XTListUtils.isEmpty(buildingEventVO.getFiles())) {
			fileService.updateList(buildingEventVO.getFiles(), buildingEventEO.getId(), BuildingEventEO.class.getName());
		} 
    }

    private String getContent(Long id) {
        ContentEO content = contentService.queryContentByTypeAndId(BusinessEnum.TYPE_EVENT.getCode(), id);
        if (content != null) {
            return content.getContent();
        }
        return null;
    }

    @Override
    public BuildingEventVO getInfo(Long id) throws XTBusinessException {
        BuildingEventEO buildingEventEO = super.getByPrimaryKey(id);
        if (buildingEventEO != null) {
            BuildingEventVO vo = new BuildingEventVO();
            BeanUtils.copyProperties(buildingEventEO, vo);
            vo.setBasicFunction(getContent(id));
        	List<FileEO> files = fileService.getFileById(id, RemoveEO.class.getName(), null);
			if (!XTListUtils.isEmpty(files)) {
				vo.setFileAction(FileUrlAdapter.assemblyAction(files.get(0).getId()));
				vo.setFiles(XTEntityUtils.getIdList(files));
			}
            return vo;
        }

        return null;
    }

    @Override
    public PagedResult<BuildingEventUsersVO> findBuildingEventUsersPagination(BuildingEventUsersEO buildingEventUsersEO) {
        Integer pageNo = buildingEventUsersEO.getPageNo() == null ? 1 : buildingEventUsersEO.getPageNo();
        Integer pageSize = buildingEventUsersEO.getPageSize() == null ? 15 : buildingEventUsersEO.getPageSize();
        List<BuildingEventUsersVO> buildingEventUsersVOS = null;
        PagedResult<BuildingEventUsersVO> page = null;
        PageHelper.startPage(pageNo, pageSize);
        List<BuildingEventUsersEO> list = buildingEventUsersService.selectPagination(buildingEventUsersEO);
        if (!CollectionUtils.isEmpty(list)) {
            List<Long> ids = list.stream().map(buildingEventUsersEOS1 -> buildingEventUsersEOS1.getUserId()).distinct().collect(Collectors.toList());
            //查詢用戶照片
            if (!CollectionUtils.isEmpty(ids)) {
                Map<Long, FileEO> files = fileService.getMapTopOne(ids, SysUser.class.getName(), null);
                Map<Long,SysUser> sysUserMap = sysUserService.getMapTopOne(ids);
                buildingEventUsersVOS = new ArrayList<BuildingEventUsersVO>();
                for (BuildingEventUsersEO buildingEventUsersEO1 : list) {
                    BuildingEventUsersVO buildingEventUsersVO = new BuildingEventUsersVO();
                    BeanUtils.copyProperties(buildingEventUsersEO1, buildingEventUsersVO);
                    FileEO file = files.get(buildingEventUsersVO.getId());
                    if (file != null) {
                        if (file.getId() > 0) {
                            buildingEventUsersVO.setHeadImage("/file/showImage/" + file.getId());
                        } else {
                            buildingEventUsersVO.setHeadImage("/image/defualt.png");
                        }
                    } else {
                        buildingEventUsersVO.setHeadImage("/image/defualt.png");
                    }

                    buildingEventUsersVO.setSysUser(sysUserMap.get(buildingEventUsersVO.getUserId()));

                    buildingEventUsersVOS.add(buildingEventUsersVO);
                }
            }

            page = PagedBeanUtil.toPagedResult(buildingEventUsersVOS);
        }


        return page;
    }

    private void initFile(List<BuildingEventVO> list){
        List<Long> ids = list.stream().map(buildingEventVO -> buildingEventVO.getId()).distinct().collect(Collectors.toList());
        List<FileEO> fileList = fileService.getFileByIds(ids,BuildingEventEO.class.getName(),null);
        if (CollectionUtils.isEmpty(fileList)){
            return;
        }

        for (BuildingEventVO buildingEventVO : list){
            for (FileEO fileEO : fileList){
                if (buildingEventVO.getId().equals(fileEO.getCaseId())){
                    buildingEventVO.setFileId(fileEO.getId());
                    continue;
                }
            }
        }
    }

    private List<BuildingEventVO> queryList(Long limit,String type,List<Long> ids){
        List<BuildingEventVO> list = Lists.newArrayList();
        List<BuildingEventEO> eventEOList = Lists.newArrayList();
        if (type.equals(TYPE_START)){
            eventEOList = buildingEventMapper.queryBuildingEventForStart(new Date(),ids);
        }else {
            eventEOList = buildingEventMapper.queryBuildingEventForOver(new Date(),ids);
        }

        if (CollectionUtils.isEmpty(eventEOList)){
            return list;
        }

        if (limit != null){
            eventEOList = eventEOList.stream().limit(limit).collect(Collectors.toList());
        }

        BuildingEventVO buildingEventVO ;
        for (BuildingEventEO buildingEventEO : eventEOList){
            buildingEventVO = new BuildingEventVO();
            BeanUtils.copyProperties(buildingEventEO,buildingEventVO);
            list.add(buildingEventVO);
        }

        //组装
        List<Long> caseIds = eventEOList.stream().map(buildingEventEO -> buildingEventEO.getId()).distinct().collect(Collectors.toList());
        List<FileEO> fileList = fileService.getFileByIds(caseIds,BuildingEventEO.class.getName(),null);
        if (CollectionUtils.isEmpty(fileList)){
            return list;
        }

        for (BuildingEventVO vo : list){
            for (FileEO fileEO : fileList){
                if (vo.getId().equals(fileEO.getCaseId())){
                    vo.setFileId(fileEO.getId());
                    vo.setFileAction(FileUrlAdapter.assemblyAction(fileEO.getId()));
                    continue;
                }
            }
        }
        return list;
    }
}
